<template>
  <div class="controls">
    <input autocomplete="off" class="itxt" :value="currentValue" @blur="handleInputEvent" @keyup.enter="handleInputEvent" />
    <button class="plus" @click="setCurrentValue(1)" :disabled="currentValue === max">+</button>
    <button class="mins" @click="setCurrentValue(-1)" :disabled="currentValue === min">-</button>
  </div>
</template>

<script>
/*
  1. 有最小值最大值
  2. 输入小于最小值，等于最小值
    输入大于最小值，等于最大值
  3. 输入小数，向上取整（或向下取整，都需要考虑边界值）
  4. 输入非数字，等于上一次的值
*/
export default {
  name: "InputNumber",
  props: {
    value: {
      type: Number,
      required: true,
    },
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 20,
    },
  },
  data() {
    return {
      currentValue: this.value,
    };
  },
  methods: {
    setCurrentValue(num) {
      this.currentValue += num;
    },
    handleInputEvent(e) {
      this.currentValue = e.target.value;
    },
  },
  watch: {
    currentValue(newVal, oldVal) {
      const { min, max } = this;
      let newValue = Math.ceil(+newVal);

      if (Number.isNaN(newValue)) {
        // if (newValue !== newValue) {
        newValue = oldVal;
      }

      if (newValue < min) {
        newValue = min;
      } else if (newValue > max) {
        newValue = max;
      }

      this.currentValue = newValue;
      this.$emit("input", newValue);
    },
  },
};
</script>

<style lang="less" scoped>
.controls {
  width: 48px;
  position: relative;
  float: left;
  margin-right: 15px;

  .itxt {
    width: 38px;
    height: 37px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
  }

  .plus,
  .mins {
    width: 15px;
    text-align: center;
    height: 17px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    position: absolute;
    right: -8px;
    border: 1px solid #ccc;
    cursor: pointer;
  }

  .mins {
    right: -8px;
    top: 19px;
    border-top: 0;
  }

  .plus {
    right: -8px;
  }

  .plus:disabled,
  .mins:disabled {
    color: #ccc;
    cursor: not-allowed;
  }
}
</style>
